#!/bin/bash
# Catalina Recovery HD Partition 
# Copyright (c) 2019, chris1111 All right reserved.
# dm Tools Copyright (c) 2017, Apple <www.apple.com.> 
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.

# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Vars
PARENTDIR=$(dirname "$0")
cd "$PARENTDIR"
echo "-------------------------------------"

apptitle="Catalina Recovery HD Partition"
version="1.0"
# Set Icon directory and file 
iconfile="/System/Library/CoreServices/Installer.app/Contents/Resources/Installer.icns"

if [ "/tmp/RecoveryHDMeta.sparseimage" ]; then
	rm -rf "/tmp/RecoveryHDMeta.sparseimage"
fi


if [ "/tmp/RecoveryHDMeta.dmg" ]; then
	rm -rf "/tmp/RecoveryHDMeta.dmg"
fi


# Select Erase
response=$(osascript -e 'tell app "System Events" to display dialog "The first step is to select your USB key\n\nSelect USB to continue Cancel for Quit" buttons {"Cancel","USB"} default button 2 with title "'"$apptitle"' '"$version"'" with icon POSIX file "'"$iconfile"'"  ')

action=$(echo $response | cut -d ':' -f2)

# Exit if Canceled
if [ "$action" == "Cancel" ] ; then
  osascript -e 'display notification "Program closing" with title "'"$apptitle"'" subtitle "User cancelled"'
  exit 0
fi

### : Select usbdisk location
if [ "$action" == "USB" ] ; then

  # Get input folder of usbdisk disk 
  usbdiskpath=`/usr/bin/osascript << EOT
    tell application "Finder"
        activate
        set folderpath to choose folder default location "/Volumes" with prompt "Select your USB key"
    end tell 
    return (posix path of folderpath) 
  EOT`

  # Cancel is user selects Cancel
  if [ ! "$usbdiskpath" ] ; then
    osascript -e 'display notification "Program closing" with title "'"$apptitle"'" subtitle "User cancelled"'
    exit 0
  fi

  # Parse vars
  inputfile=$imagepath

  # Check if Compressed from extension
  extension="${inputfile##*.}"
  if [ "$extension" == "gz" ] || [ "$extension" == "zip" ] || [ "$extension" == "xz" ]; then
    compression="Yes"
  else
    compression="No"
  fi

fi

# Parse usbdisk disk volume
usbdisk=$( echo $usbdiskpath | awk -F '\/Volumes\/' '{print $2}' | cut -d '/' -f1 )
disknum=$( diskutil list | grep "$usbdisk" | awk -F 'disk' '{print $2}' | cut -d 's' -f1 )
devdisk="/dev/disk$disknum"
# use rdisk for faster copy
devdiskr="/dev/rdisk$disknum"
# Get Drive size
drivesize=$( diskutil list | grep "disk$disknum" | grep "0\:" | cut -d "*" -f2 | awk '{print $1 " " $2}' )

# Set output option
if [ "$action" == "USB" ] ; then
  source=$inputfile
  dest="$drivesize $usbdisk (disk$disknum)"
  outputfile=$devdiskr
  check=$source
fi

# Confirmation Dialog
response=$(osascript -e 'tell app "System Events" to display dialog "Please confirm your choice and click OK\n\nDestination: \n'"$dest"' \n\n\nNOTE:The USB key will be formatted into a single partition, the data will be erased!" buttons {"Cancel", "OK"} default button 2 with title "'"$apptitle"' '"$version"'" with icon POSIX file "'"$iconfile"'" ')
answer=$(echo $response | grep "OK")

# Cancel is user does not select OK
if [ ! "$answer" ] ; then
  osascript -e 'display notification "Program closing" with title "'"$apptitle"'" subtitle "User cancelled"'
  exit 0
fi

# Unmount Volume
response=$(diskutil unmountDisk $devdisk)
answer=$(echo $response | grep "successful")

# Cancel if unable to unmount
if [ ! "$answer" ] ; then
  osascript -e 'display notification "Program closing" with title "'"$apptitle"'" subtitle "Cannot Unmount '"$usbdisk"'"'
  exit 0
fi


# script Notifications
osascript -e 'display notification "Format" with title "USB"  sound name "default"'

diskutil partitiondisk "$outputfile" 1 GPTFormat JHFS+ USB-RECOVERY 100% 

# script Notifications
osascript -e 'display notification "'"$drivesize"' Format Volume '$action' Completed " with title "'"$apptitle"'" subtitle " '"$fname"' "'


# Select Install macOS
response=$(osascript -e 'tell app "System Events" to display dialog "Select Install macOS to choose your Install macOS Catalina.app\n\nCancel for Quit" buttons {"Cancel","Install macOS"} default button 2 with title "'"$apptitle"' '"$version"'" with icon POSIX file "'"$iconfile"'"  ')

action=$(echo $response | cut -d ':' -f2)


# Get image file location
  imagepath=`/usr/bin/osascript << EOT
    tell application "Finder"
        activate
        set imagefilepath to choose file default location "/Applications" with prompt "Choose the location of your Install macOS Catalina.app"
    end tell 
    return (posix path of imagefilepath) 
  EOT`

  # Cancel is user selects Cancel
  if [ ! "$imagepath" ] ; then
    osascript -e 'display notification "Program closing" with title "'"$apptitle"'" subtitle "User cancelled"'
    exit 0
  fi

hdiutil attach "$imagepath"/Contents/SharedSupport/InstallESD.dmg -noverify -nobrowse -mountpoint /tmp/Installer-OS

hdiutil attach "$imagepath"/Contents/SharedSupport/BaseSystem.dmg -noverify -nobrowse -mountpoint /tmp/Base-OS



# Remove the image if exist
if [[ $(mount | awk '$3 == "/Volumes/RecoveryHDMeta" {print $3}') != "" ]]; then
 hdiutil detach "/Volumes/RecoveryHDMeta"
fi

if [ "/tmp/RecoveryHDMeta.sparseimage" ]; then
	rm -rf "/tmp/RecoveryHDMeta.sparseimage"
fi

if [ "/tmp/RecoveryHDMeta.dmg" ]; then
	rm -rf "/tmp/RecoveryHDMeta.dmg"
fi

echo "
***********************************************************
Create image for macOS Recovery HD
***********************************************************  "

# Create the Recovery HD for HFS+J/APFS/CS
hdiutil create -size 600m -type SPARSE -fs HFS+J -volname RecoveryHDMeta -uid 0 -gid 80 -mode 1775 /tmp/RecoveryHDMeta

# Attach image
hdiutil attach -nobrowse /tmp/RecoveryHDMeta.sparseimage


rsync -a --progress "$imagepath/Contents/SharedSupport/BaseSystem.dmg" "/Volumes/RecoveryHDMeta"
rsync -a --progress "$imagepath/Contents/SharedSupport/AppleDiagnostics.chunklist" "/Volumes/RecoveryHDMeta"
rsync -a --progress "$imagepath/Contents/SharedSupport/BaseSystem.chunklist" "/Volumes/RecoveryHDMeta"
rsync -a --progress "$imagepath/Contents/SharedSupport/AppleDiagnostics.dmg" "/Volumes/RecoveryHDMeta"
Sleep 2



echo "
***********************************************************
Recovery HD Partition image completed
***********************************************************  "

# Unmount Image
hdiutil detach -Force /Volumes/RecoveryHDMeta

# Convert Image
hdiutil convert /tmp/RecoveryHDMeta.sparseimage -format UDZO -o /tmp/RecoveryHDMeta.dmg

# Unmount image
hdiutil detach -Force /tmp/Installer-OS

# Unmount image
hdiutil detach -Force /tmp/Base-OS


echo "
***********************************************************  "

# script Notifications
osascript -e 'display notification "" with title "Catalina Recovery HD Partition" '

Open ./"Recovery HD Partition.pkg"
 

exit
